# Django框架导入
from django import forms
from django.db.models import Q
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password

# 本地模型导入
from .models import (
    CustomUser, Company, Department, Factory, Technology,
    Materialtype, Warehouse, Place, Material, Inventory,
    Device, InventoryRecord
)

class CustomUserCreationForm(UserCreationForm):
    username = forms.CharField(max_length=30, required=True, label='账号')
    password1 = forms.CharField(widget=forms.PasswordInput, label='密码')
    password2 = forms.CharField(widget=forms.PasswordInput, label='确认密码')
    realname = forms.CharField(max_length=30, required=True, label='姓名')
    phone_number = forms.CharField(max_length=11, required=True, label='手机号')
    is_manager = forms.BooleanField(required=False, label='管理员')
    is_broad = forms.BooleanField(required=False, label='管理全域')
    is_approver = forms.BooleanField(required=False, label='有审批权')
    is_deviceoperator = forms.BooleanField(required=False, label='设备权')
    is_inventoryoperator = forms.BooleanField(required=False, label='物料权')
    can_add_device = forms.BooleanField(required=False, label='可添加设备')
    department = forms.ModelChoiceField(queryset=None, required=True, label='所属县区')
    company = forms.ModelChoiceField(queryset=None, required=True, label='所属地市')

    class Meta:
        model = CustomUser
        fields = ['username', 'password1', 'password2', 'realname', 'phone_number', 'is_manager', 
                  'is_broad', 'is_approver', 'is_deviceoperator', 'is_inventoryoperator', 
                  'can_add_device', 'department', 'company']

    def __init__(self, *args, **kwargs):
        current_user = kwargs.pop('current_user', None)
        super().__init__(*args, **kwargs)
        
        # 根据当前用户所属company获取department
        self.fields['department'].queryset = current_user.company.department_set.all()
        self.fields['company'].queryset = current_user.company.__class__.objects.all()


        
        # 超级用户可设置is_manager，普通管理员不可
        if not current_user.is_superuser:
            self.fields['is_manager'].disabled = True
            self.fields['is_manager'].initial = False
            self.fields['is_manager'].help_text = '仅超级用户可设置'

class SuperCompanyForm(forms.ModelForm):
    class Meta:
        model = Company
        fields = ['company']
        widgets = {
            'company': forms.TextInput(attrs={'class': 'form-control'})
        }

class SuperDepartmentForm(forms.ModelForm):
    class Meta:
        model = Department
        fields = ['department', 'company']
        widgets = {
            'department': forms.TextInput(attrs={'class': 'form-control'}),
            'company': forms.Select(attrs={'class': 'form-select'})
        }

class SuperCustomUserCreationForm(UserCreationForm):
    class Meta:
        model = CustomUser
        fields = ['username', 'password1', 'password2', 'realname', 'phone_number', 
                  'is_manager', 'is_broad', 'is_approver', 'is_deviceoperator', 
                  'is_inventoryoperator', 'can_add_device', 'department', 'company']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 设置字段属性
        self.fields['username'].label = '账号'
        self.fields['password1'].label = '密码'
        self.fields['password2'].label = '确认密码'
        self.fields['realname'].label = '姓名'
        self.fields['phone_number'].label = '手机号'
        
        # 设置默认值并隐藏字段
        self.fields['is_manager'].initial = True
        self.fields['is_manager'].widget = forms.HiddenInput()
        
        self.fields['is_broad'].initial = True
        self.fields['is_broad'].widget = forms.HiddenInput()
        
        self.fields['is_approver'].initial = True
        self.fields['is_approver'].widget = forms.HiddenInput()
        
        self.fields['is_deviceoperator'].initial = True
        self.fields['is_deviceoperator'].widget = forms.HiddenInput()
        
        self.fields['is_inventoryoperator'].initial = True
        self.fields['is_inventoryoperator'].widget = forms.HiddenInput()
        
        self.fields['can_add_device'].initial = True
        self.fields['can_add_device'].widget = forms.HiddenInput()
        
        self.fields['department'].label = '所属县区'
        self.fields['company'].label = '所属地市'

    def clean_password1(self):
        password1 = self.cleaned_data.get('password1')
        try:
            validate_password(password1, self.instance)
        except ValidationError as e:
            raise ValidationError(e.messages)
        return password1

    def clean(self):
        cleaned_data = super().clean()
        password1 = cleaned_data.get('password1')
        password2 = cleaned_data.get('password2')

        if password1 and password2 and password1 != password2:
            raise ValidationError("两次输入的密码不一致")

        username = cleaned_data.get('username')
        if username and password1 and username in password1:
            raise ValidationError("密码不能包含用户名")

        return cleaned_data     

class DepartmentForm(forms.ModelForm):
    class Meta:
        model = Department
        fields = ['department']

    def __init__(self, *args, **kwargs):
        self.current_user = kwargs.pop('current_user', None)
        super().__init__(*args, **kwargs) 

class FactoryForm(forms.ModelForm):
    class Meta:
        model = Factory
        fields = ['factory']

    def __init__(self, *args, **kwargs):
        self.current_user = kwargs.pop('current_user', None)
        super().__init__(*args, **kwargs)  

class TechnologyForm(forms.ModelForm):
    class Meta:
        model = Technology
        fields = ['technology']

    def __init__(self, *args, **kwargs):
        self.current_user = kwargs.pop('current_user', None)
        super().__init__(*args, **kwargs)

class MaterialtypeForm(forms.ModelForm):
    class Meta:
        model = Materialtype
        fields = ['materialtype']

    def __init__(self, *args, **kwargs):
        self.current_user = kwargs.pop('current_user', None)
        super().__init__(*args, **kwargs)

class WarehouseForm(forms.ModelForm):
    class Meta:
        model = Warehouse
        fields = ['warehouse', 'department']

    def __init__(self, *args, **kwargs):
        self.current_user = kwargs.pop('current_user', None)
        super().__init__(*args, **kwargs)
        # 根据当前用户所属company获取department
        self.fields['department'].queryset = self.current_user.company.department_set.all()

class PlaceForm(forms.ModelForm):
    class Meta:
        model = Place
        fields = ['place', 'department', 'attribute']

    def __init__(self, *args, **kwargs):
        self.current_user = kwargs.pop('current_user', None)
        super().__init__(*args, **kwargs)
        # 根据当前用户所属company获取department
        self.fields['department'].queryset = self.current_user.company.department_set.all()


class MaterialForm(forms.ModelForm):
    class Meta:
        model = Material
        fields = ['material', 'specification', 'measureunit', 'materialtype']

    def __init__(self, *args, **kwargs):
        self.current_user = kwargs.pop('current_user', None)
        super().__init__(*args, **kwargs)
        # 根据当前用户所属company获取materialtype
        self.fields['materialtype'].queryset = self.current_user.company.materialtype_set.all()


class InventoryFilterForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super().__init__(*args, **kwargs)

    def filter_queryset(self, queryset=None):
        queryset = queryset if queryset is not None else Inventory.objects.all()
        if not self.user.is_broad:
            queryset = queryset.filter(department=self.user.department)
        else:
            queryset = queryset.filter(company=self.user.company)
        
        return queryset
    


class DeviceFilterForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super().__init__(*args, **kwargs)

    def filter_queryset(self, queryset=None):
        queryset = queryset if queryset is not None else Device.objects.all()
        if not self.user.is_broad:
            queryset = queryset.filter(department=self.user.department)
        else:
            queryset = queryset.filter(company=self.user.company)
        return queryset


class DeviceCreateForm(forms.ModelForm):
    class Meta:
        model = Device
        fields = ['number', 'model', 'factory', 'technology', 'place', 'state', 'mac', 'summary', 'cust_code', 'cust_name', 'project']

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super().__init__(*args, **kwargs)
        self.fields['number'].disabled = True  # 禁用number字段

        # 根据用户权限过滤place
        if not self.user.is_broad:
            self.fields['place'].queryset = Place.objects.filter(department=self.user.department)
        else:
            self.fields['place'].queryset = Place.objects.filter(company=self.user.company)

        # 过滤factory和technology
        self.fields['factory'].queryset = Factory.objects.filter(company=self.user.company)
        self.fields['technology'].queryset = Technology.objects.filter(company=self.user.company)

class UserEditForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = ['realname', 'phone_number', 'is_broad', 'is_approver', 
                 'is_deviceoperator', 'is_inventoryoperator', 'can_add_device', 
                 'department']

    def __init__(self, *args, **kwargs):
        self.current_user = kwargs.pop('current_user')
        super().__init__(*args, **kwargs)
        
        # 限制department的取值为当前用户所在company的department
        self.fields['department'].queryset = Department.objects.filter(company=self.current_user.company)


class InventoryRecordFormOLD(forms.ModelForm):
    transfer_warehouse = forms.ModelChoiceField(
        queryset=Warehouse.objects.none(),  # 初始为空，在视图中设置
        required=False,
        label='调拨目标仓库'
    )
    
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        if user and user.company:
            # 只显示当前用户所属公司的仓库
            self.fields['transfer_warehouse'].queryset = Warehouse.objects.filter(company=user.company)

    class Meta:
        model = InventoryRecord
        fields = ['operatemode', 'quantity', 'operatedate', 'reason'] 

class InventoryRecordForm(forms.ModelForm):
    class Meta:
        model = InventoryRecord
        fields = ['operatemode', 'quantity', 'operatedate', 'reason', 'transfer_warehouse']
        widgets = {
            'operatedate': forms.DateInput(attrs={'type': 'date'}),
        }

    def __init__(self, *args, **kwargs):
        inventory = kwargs.pop('inventory', None)
        super().__init__(*args, **kwargs)
        if inventory:
            # 过滤掉当前仓库
            company = inventory.company 
            current_warehouse_id = inventory.warehouse.id            
            self.fields['transfer_warehouse'].queryset = Warehouse.objects.filter(
                company=company
            ).exclude(id=current_warehouse_id)
    transfer_warehouse = forms.ModelChoiceField(
        queryset=Warehouse.objects.none(),
        required=False,
        label='调入仓库'
    )

class DeviceAdjustForm(forms.ModelForm):
    placenow = forms.ModelChoiceField(
        queryset=Place.objects.all(),
        label='新位置',
        required=True
    )
    statenow = forms.ChoiceField(
        choices=[(1, '正常'), (2, '故障')],
        label='新状态',
        required=True
    )
    reason = forms.CharField(
        label='调整原因',
        max_length=100,
        required=True,
        widget=forms.Textarea(attrs={'rows': 3})
    )

    class Meta:
        model = Device
        fields = []

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 设置初始值
        if self.instance:
            self.fields['placenow'].initial = self.instance.place
            self.fields['statenow'].initial = self.instance.state

class DeviceUpdateForm(forms.ModelForm):
    class Meta:
        model = Device 
        exclude = ['create_date', 'create_user','update_date', 'attribute', 'area', 'place', 'state', 'factory', 'technology', 'company', 'department', 'company']